import * as https from "https";
import { gunzip } from "zlib";
import { FORUM_NOT_FOUND } from "./apis";

export default function adrequest(url: string, successCallback?: ((data: any) => void), failCallback?: Function): void {
  https.get(url, (res) => {
    console.log("StatusCode:" + res.statusCode);
    if (res.statusCode === 301) {
      if (res.headers.location) {
        console.log("地址已跳转！");
        return adrequest(res.headers.location, successCallback, failCallback);
      } else {
        console.error(JSON.stringify(res));
        return failCallback && failCallback(new Error("未知错误，请查看日志。"));
      }
    }
    if (res.statusCode !== 200) {
      // vscode.window.showErrorMessage("错误：" + res.statusCode);
      console.error(JSON.stringify(res));
      return failCallback && failCallback(new Error("未知错误，请查看日志。"));
    }
    // 对接口返回数据进行处理
    let rawData: Uint8Array[] = [];
    res.on("data", (data) => {
      rawData.push(data);
    });
    res.on("error", (e) => {
      console.error(e);
      failCallback && failCallback(new Error("网络错误，请查看日志。"));
    });
    res.on("end", () => {
      if (res.headers["content-encoding"] === 'gzip') {
        try {
          let buffer = Buffer.concat(rawData);
          gunzip(buffer, (err, decoded) => {
            let decodedData = JSON.parse(decoded.toString());
            console.log("成功解析数据：", decodedData);
            // 使用成功回调函数
            // 对成功数据进行回调
            successCallback && successCallback(decodedData);
          });
        } catch (e) {
          console.error(e);
          failCallback && failCallback(new Error("数据解析错误，请查看日志！"));
        }
      } else {
        try {
          if (rawData.toString() === FORUM_NOT_FOUND) {
            console.error("板块不存在");
            failCallback && failCallback(new Error("板块不存在"));
          } else {
            let decodedData = JSON.parse(rawData.toString());
            console.log("成功解析数据：", decodedData);
            successCallback && successCallback(decodedData);
          }
        } catch (e) {
          console.error(e);
          failCallback && failCallback(new Error("数据解析错误，请查看日志！"));
        }
      }
    });
  });
}